public class CoinChange {
    // 零钱兑换
    // https://leetcode.cn/problems/coin-change/description/?envType=study-plan-v2&envId=top-100-liked
    public int coinChange(int[] coins, int amount) {
        // 完全背包问题
        // dp[i][j] = Math.min(dp[i-1][j], dp[i][j-coins[i]]+1)
        int n = coins.length;
        int[][] dp = new int[n+1][amount+1];
        // 初始化，要想让第一行不影响填表，应初始化为最大值，dp[0][0]=0
        int INF = 0x3f3f3f3f;
        for (int j = 1; j < amount+1; j++) dp[0][j] = INF;
        for (int i = 1; i < n+1; i++) {
            for (int j = 0; j < amount+1; j++) {
                dp[i][j] = dp[i-1][j];
                if (j >= coins[i-1]) {
                    dp[i][j] = Math.min(dp[i][j], dp[i][j-coins[i-1]] + 1);
                }
            }
        }
        return dp[n][amount] == INF ? -1 : dp[n][amount];
    }

    // 空间优化
    public int coinChange1(int[] coins, int amount) {
        // 完全背包问题
        // dp[i][j] = Math.min(dp[i-1][j], dp[i][j-coins[i]]+1)
        int n = coins.length;
        int[] dp = new int[amount+1];
        // 初始化，要想让第一行不影响填表，应初始化为最大值，dp[0][0]=0
        int INF = 0x3f3f3f3f;
        for (int j = 1; j < amount+1; j++) dp[j] = INF;
        for (int i = 1; i < n+1; i++) {
            for (int j = coins[i-1]; j < amount+1; j++) {
                dp[j] = Math.min(dp[j], dp[j-coins[i-1]] + 1);
            }
        }
        return dp[amount] == INF ? -1 : dp[amount];
    }
}
